package baidu.com.matedemo.dlp;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;

import com.baidu.duer.libcore.adapter.CommonAdapter;
import com.baidu.duer.libcore.adapter.ViewHolder;
import com.baidu.duer.libcore.util.DisplayUtil;
import com.baidu.duer.libcore.view.swipe.SwipeMenu;
import com.baidu.duer.libcore.view.swipe.SwipeMenuCreator;
import com.baidu.duer.libcore.view.swipe.SwipeMenuItem;
import com.baidu.duer.libcore.view.swipe.SwipeMenuListView;
import com.baidu.duer.smartmate.protocol.dlp.bean.screen.BaseRenderAlertBean;
import com.baidu.duer.smartmate.protocol.dlp.bean.screen.RenderAlarmListPayload;
import com.baidu.duer.smartmate.protocol.dlp.bean.screen.RenderPayload;
import com.baidu.duer.smartmate.protocol.dlp.bean.screen.RenderTimerListPayload;
import com.baidu.duer.smartmate.protocol.dlp.bean.screen.RenderType;
import com.baidu.duer.smartmate.proxy.SendMessageStatus;
import com.baidu.duer.smartmate.proxy.bean.AlertMessage;
import com.baidu.duer.smartmate.proxy.controller.ControllerManager;
import com.baidu.duer.smartmate.proxy.controller.DCSDataObserver;
import com.baidu.duer.smartmate.proxy.inter.ISendMessageHandler;
import com.google.gson.internal.bind.util.ISO8601Utils;

import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import baidu.com.matedemo.DemoApp;
import baidu.com.matedemo.R;
import baidu.com.matedemo.base.ListBaseFragment;

/**
 * Created by lihui38 on 2017/12/22.
 */

public class RenderAlertDemo extends ListBaseFragment implements DCSDataObserver<RenderPayload> {

    ControllerManager controllerManager;
    List<BaseRenderAlertBean> dataList = new ArrayList<>();
    List<RenderAlarmListPayload.Alarm> alarmList = new ArrayList<>();
    List<RenderTimerListPayload.Timer> timerList = new ArrayList<>();

    private boolean isThreadStarted = false;
    private boolean isLooping = true;
    private boolean isSwiping = false;
    private Handler mainLoopHandler = new Handler(Looper.getMainLooper());

    CommonAdapter<BaseRenderAlertBean> adapter;

    @Override
    public void onViewCreated(View view) {

        getListView().addHeaderView(LayoutInflater.from(getMActivity()).inflate(R.layout.render_alert_header, null));

        controllerManager = DemoApp.getInstance().getCurreDuerDevice().getControllerManager();
        controllerManager.registerRenderObserver(this);
        controllerManager.registerAlertObserver(alertDCSDataObserver);

        adapter = new CommonAdapter<BaseRenderAlertBean>(getMActivity(), R.layout.item_alert, dataList) {
            @Override
            protected void convert(ViewHolder viewHolder, final BaseRenderAlertBean alertBean, int i) {
                if (alertBean instanceof RenderAlarmListPayload.Alarm) {
                    RenderAlarmListPayload.Alarm alarm = (RenderAlarmListPayload.Alarm) alertBean;
                    viewHolder.setText(R.id.alert_time, alarm.getFormattedTime());
                    viewHolder.setText(R.id.alert_date, alarm.getFormattedDate());
                    viewHolder.setText(R.id.alert_type, alarm.getMessage());
                } else if (alertBean instanceof RenderTimerListPayload.Timer) {
                    RenderTimerListPayload.Timer timer = (RenderTimerListPayload.Timer) alertBean;
                    long curTimeInMillisecond = System.currentTimeMillis();
                    long remains = timer.getScheduledTimeInMillisecond() - curTimeInMillisecond;
                    if (remains < 0) remains = 0;
                    String formatRemains = format(remains);
                    viewHolder.setText(R.id.alert_time, formatRemains);
                    viewHolder.setText(R.id.alert_date, "剩余时间");
                    viewHolder.setText(R.id.alert_type, "计时器");
                }
            }
        };

        setAdapter(adapter);

        if (getListView() != null) {
            getListView().setSelector(new ColorDrawable(Color.TRANSPARENT));
            SwipeMenuCreator creator = new SwipeMenuCreator() {
                @Override
                public void create(SwipeMenu menu) {
                    SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
                    deleteItem.setBackground(R.color._ff3b30);
                    deleteItem.setWidth(DisplayUtil.dip2px(getContext(), 90));
                    deleteItem.setTitle("删除");
                    deleteItem.setTitleSize(16);
                    deleteItem.setMarginTop(DisplayUtil.dip2px(getContext(), 10));
                    deleteItem.setTitleColor(getResources().getColor(R.color.vpi_white));
                    menu.addMenuItem(deleteItem);
                }
            };

            // set creator
            if (getListView() instanceof SwipeMenuListView) {
                ((SwipeMenuListView) getListView()).setMenuCreator(creator);
                ((SwipeMenuListView) getListView()).setOnMenuItemClickListener(swipeListener);
                ((SwipeMenuListView) getListView()).setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
                    @Override
                    public void onMenuOpen(int i) {
                        isSwiping = true;
                    }

                    @Override
                    public void onMenuClose(int i) {
                        isSwiping = false;
                    }
                });
            }
        }

        // 刷新数据
        refreshData();
    }

    private DCSDataObserver<AlertMessage> alertDCSDataObserver = new DCSDataObserver<AlertMessage>() {
        @Override
        public void onDataChanaged(String event, AlertMessage message) {
            if (AlertMessage.ALERT_STARTED.equals(event)) { // 音箱上的定时器已经开始响铃，更新本地定时器数据
                for (RenderTimerListPayload.Timer item : timerList) {
                    if (!TextUtils.isEmpty(item.getToken()) && item.getToken().equals(message.getToken())) {
                        item.setScheduledTimeInMillisecond(System.currentTimeMillis());
                        break;
                    }
                }
                updateDataList();
            } else if (AlertMessage.ALERT_STOPPED.equals(event)) { // 此时云端会清除这一条定时器数据，再请求一次云端获取最新数据
                refreshData();
            }
        }
    };

    private SwipeMenuListView.OnMenuItemClickListener swipeListener = new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(int position, SwipeMenu swipeMenu, int i1) {
            if (controllerManager != null) {
                final BaseRenderAlertBean baseBean = dataList.get(position);
                if (baseBean == null) return false;
                if (baseBean instanceof RenderAlarmListPayload.Alarm) {
                    controllerManager.deleteRenderAlarm(baseBean.getToken(), new ISendMessageHandler() {
                        @Override
                        public void onStatus(SendMessageStatus status, String message) {
                            if (status == SendMessageStatus.SUCCESS) {
                                dataList.remove(baseBean);
                                alarmList.remove((RenderAlarmListPayload.Alarm) baseBean);
                            }
                            getAdapter().notifyDataSetChanged();
                        }
                    });
                } else if (baseBean instanceof RenderTimerListPayload.Timer) {
                    controllerManager.deleteRenderTimer(baseBean.getToken(), new ISendMessageHandler() {
                        @Override
                        public void onStatus(SendMessageStatus status, String message) {
                            if (status == SendMessageStatus.SUCCESS) {
                                dataList.remove(baseBean);
                                timerList.remove((RenderTimerListPayload.Timer) baseBean);
                            }
                            getAdapter().notifyDataSetChanged();
                        }
                    });
                }
            }
            isSwiping = false;
            return false;
        }
    };

    private BaseAdapter getAdapter() {
        return adapter;
    }

    public void refreshData() {
        if (controllerManager != null) {
            controllerManager.getRenderAlarmList();
            controllerManager.getRenderTimerList();
        }
    }

    @Override
    public void onDataChanaged(String event, RenderPayload message) {
        if (message == null) return;

        if (message.getRenderType() == RenderType.REDNER_ALARM_LIST || message.getRenderType() == RenderType.RENDER_TIMER_LIST) { // 过滤例如 UNKNOWN 这种TYPE的消息
            if (message instanceof RenderAlarmListPayload) {
                alarmList.clear();
                List<RenderAlarmListPayload.Alarm> alarms = ((RenderAlarmListPayload) message).getAlarms();
                alarmList.addAll(alarms);
                updateDataList();
            } else if (message instanceof RenderTimerListPayload) {
                timerList.clear();
                List<RenderTimerListPayload.Timer> timers = ((RenderTimerListPayload) message).getTimers();
                for (RenderTimerListPayload.Timer item : timers) {
                    try {
                        Date date = ISO8601Utils.parse(item.getScheduledTime(), new ParsePosition(0));
                        /**
                         * !!!!! timeInMillisecond 成员变量默认不赋值，即这个变量是自己换算而成的，而不是后端直接推给我们的数据
                         */
                        item.setScheduledTimeInMillisecond(date.getTime());
                    } catch (Exception e) {
                    }

                }
                timerList.addAll(timers);
                updateDataList();
            }
        }
    }

    private synchronized void updateDataList() {
        dataList.clear();
        dataList.addAll(alarmList); // 闹钟数据在前
        dataList.addAll(timerList);

        if (!dataList.isEmpty() && mThread != null && !isThreadStarted) {
            mThread.start();
        }
        getAdapter().notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isLooping = false;
        isThreadStarted = false;
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
    }


    private Thread mThread = new Thread(new Runnable() {
        @Override
        public void run() {

            isThreadStarted = true;

            while (isLooping) {
                if (!dataList.isEmpty()) {
                    mainLoopHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (!isSwiping) {
                                getAdapter().notifyDataSetChanged();
                            }
                        }
                    });
                }
//                ConsoleLogger.printDebugInfo(RenderAlertDemo.class, "-----------------------------");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }

        }
    });


    private static final String FORMAT_TIME = "%s:%s:%s";

    public static String format(long timeInMillisecond) {

        timeInMillisecond = timeInMillisecond / 1000;

        long hour = timeInMillisecond / 3600;
        long minute = timeInMillisecond / 60 % 60;
        long second = timeInMillisecond % 60 % 60;

        String hourval = hour < 10 ? "0" + hour : String.valueOf(hour);
        String minuteval = minute < 10 ? "0" + minute : String.valueOf(minute);
        String secondval = second < 10 ? "0" + second : String.valueOf(second);

        return String.format(FORMAT_TIME, hourval, minuteval, secondval);

    }
}
